package com.lx.idea.interceptor;

import com.lx.idea.common.Constant;
import com.lx.idea.common.dto.ResponseCode;
import com.lx.idea.common.dto.ResponseModel;
import com.lx.idea.common.dto.ResponseUtil;
import com.lx.idea.common.util.TokenUtil;
import com.lx.idea.model.CurrentNode;
import com.lx.idea.service.NodeServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashSet;
import java.util.Set;

/**
 * @Author ybb
 * @Description
 * @Date 2021/8/30 15:39
 */
//@Component //加上注解之后其他实例无法自动注入
@Slf4j
public class SessionInterceptor extends HandlerInterceptorAdapter{

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private NodeServiceImpl nodeService;

    @Autowired
    TokenUtil tokenUtil;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        Set<String> excludePathPatterns = new HashSet<>();
        excludePathPatterns.add("/ma-api/analysis/save");
        excludePathPatterns.add("/ma-api/analysis/del");
        //add
        String uri = request.getRequestURI();
        log.info("访问路径 =>  {}",uri);

        CurrentNode currentNode = nodeService.getCurrPrefix();
        if (currentNode.getLevel() == Constant.level_3) {
//            判断请求者ip，如果为本机ip放行，用于页面管理标识。
            String ipAddr = SessionInterceptor.getIpAddr(request);
            System.out.println("请求者源ip为 "+ ipAddr);
//            if (ipAddr.equals(nodeService.getCurrPrefix().getNodeIp())){
            if (ipAddr.equals("121.69.94.122")){
                return true;
            }
            String token = request.getHeader(Constant.token);
            if (StringUtils.isBlank(token) || !tokenUtil.verifyToken(token)) {
                ResponseUtil.renderJson(response, ResponseModel.error(ResponseCode.AUTH_TOKEN_ERROR, ResponseCode.AUTH_TOKEN_ERROR.getMessage()));
                return false;
            }
        }else if (currentNode.getLevel() == Constant.level_2){
            return true;
        } else {
            if (excludePathPatterns.contains(uri)) {
                ResponseUtil.renderJson(response, ResponseModel.error(ResponseCode.FUNC_NOT_OPEN, ResponseCode.FUNC_NOT_OPEN.getMessage()));
                return false;
            }
        }
        return true;
    }

    /**
     * 获取访问者真实IP地址
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if ("127.0.0.1".equals(ipAddress) || "0:0:0:0:0:0:0:1".equals(ipAddress)) {
                // 根据网卡取本机配置的IP
                try {
                    ipAddress = InetAddress.getLocalHost().getHostAddress();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
            }
        }
        return ipAddress;
}
}
